<template>
  <div class="m_container">
   
    <!-- 博客内容 -->
    <div class="m_content">
      <el-form ref="editForm" status-icon :model="editForm" :rules="rules1"  label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="editForm.title"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="editForm.description"></el-input>
        </el-form-item>

        <el-form-item label="首页图片" prop="first_picture">
<!--          action="/upload"-->
          <el-upload
              ref="upload"
              action="/upload"
              name="picture"
              list-type="picture-card"
              :limit="1"
              :on-exceed="onExceed"
              :before-upload="beforeUpload"
              :on-preview="handlePreview"
              :on-success="handleSuccess"
              :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>

        <el-form-item label="内容" prop="content">

          <mavon-editor :ishljs = "true" v-model="editForm.content" ref=md @save="save" @imgAdd="imgAdd" />

          <!--          <vue-ueditor-wrap v-model="msg" :config="myConfig" ></vue-ueditor-wrap>-->

          <!--          <mavon-editor ref=md v-model="editForm.content"/>-->
        </el-form-item>
        <el-form-item style="margin: auto;">
          <el-button type="info" @click="temporarySave()">暂时保存</el-button>
          <el-button type="primary" @click="tosubmitForm('editForm')">发布文章</el-button>
          <!-- <el-button>取消</el-button> -->
        </el-form-item>
      </el-form>
    </div>

   <!-- 对话框内容 -->
   <el-dialog title="发布文章" :visible.sync="dialogFormVisible" width="35%">
      <el-form :model="editForm" ref="editForm2">
        <el-form-item label="文章标签"  :label-width="formLabelWidth">
          <!-- <el-input v-model="oldtags" placeholder="请选择标签，多个标签请用逗号隔开" width="80%"></el-input> -->
          <el-tag
            :key="tag"
            v-for="tag in editForm.tags"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)">
            {{tag}}
          </el-tag>
          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          >
          </el-input>
          <el-button v-else class="button-new-tag" style="margin-left: 10px;" size="small" @click="showInput">+ New Tag</el-button>
        </el-form-item>
        <el-form-item label="分类专栏" prop="type_id" :label-width="formLabelWidth"
            :rules="{
              required: true, message: '分类专栏不能为空', trigger: 'blur'
            }">
          <el-select v-model="editForm.type_id" placeholder="请选择分类专栏">
            <el-option v-for="(item,index) in getalltype" :key="item.index" :label="item.name" :value="item.id + ''"></el-option>
          </el-select>
          <el-button type="primary" size="small" @click="dialog2 = true" style="margin-left: 10px;">新建分类专栏</el-button>
        </el-form-item>
        <el-form-item label="文章类型" prop="flag" :label-width="formLabelWidth"
            :rules="{
              required: true, message: '文章类型不能为空', trigger: 'blur'
            }">
          <el-select v-model="editForm.flag" placeholder="请选择文章类型，默认为原创">
            <el-option label="原创" value="原创"></el-option>
            <el-option label="转载" value="转载"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发布形式" prop="published" :label-width="formLabelWidth"
            :rules="{
              required: true, message: '发布形式不能为空', trigger: 'blur'
            }">
          <el-select v-model="editForm.published" placeholder="请选择发布形式，，默认为私密">
            <el-option label="私密" value=0></el-option>
            <el-option label="公开" value=1></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitBlog('editForm2')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 新建分类专栏 -->
    <el-dialog
      title="新建分类专栏"
      :visible.sync="dialog2"
      width="30%"
      >
      <el-form status-icon :model="type" ref="type" :rules="rules2" label-width="120px">
        <el-form-item label="分类专栏名" prop="name">
          <el-input v-model="type.name" placeholder="请输入要新建的分类专栏名"></el-input>
        </el-form-item>
      </el-form>
       <span slot="footer" class="dialog-footer">
          <el-button @click="dialog2 = false">取 消</el-button>
          <el-button type="primary" @click="submitForm('type')">确 定</el-button>
        </span>
    </el-dialog>


  </div>
</template>
<script>
  export default {
    name: "WriteBlog",
    data() {
      //自定义图片上传校验规则
      var checkPictures = (rule, value, callback) => { // 图片验证
        if (!this.hasImg) {
          callback(new Error('请上传图片'));
        } else {
          callback();
        }
      }
      return {
        editForm: {  //博客文章表单
          id: null,
          title: '',
          description: '',
          content: '',
          contentHtml:'',
          type_id: '',
          flag:'',
          published: null,
          tags: [],
          first_picture:'',
        },
        editForm2: {  //用来校验的表单
          type_id: null,
          flag:'',
          published: null,
        },
        oldtags:'',  //字符串类型的标签
        type:{  //分类专栏
           name:''
        },
        getalltype:[], // 所有分类专栏
        dialogFormVisible: false,  //控制发布博客对话框
        dialog2: false,  //控制新增分类专栏对话框
        rules1: {  //表单校验
          title: [
            {required: true, message: '请输入标题', trigger: 'blur'},
            {min: 3, max: 100, message: '长度在 3 到 100 个字符', trigger: 'blur'}
          ],
          description: [
            {required: true, message: '请输入摘要', trigger: 'blur'}
          ],
          first_picture: [
            {validator: checkPictures, trigger: 'blur'}
          ],
          content: [
            {required: true, message: '请输入文章内容', trigger: 'blur'}
          ],
        },
        rules2:{ //表单校验
          name: [
            {required: true, message: '分类专栏名不能为空', trigger: 'blur'}
          ],
        },
        formLabelWidth: '120px',  // 输入框的宽度
        inputVisible: false,
        inputValue: '',
        hasImg: false, //判断是否上传照片

        //  图片上传区
        //文件上传的参数
        dialogImageUrl: '',
        dialogVisible: false,
        //图片列表（用于在上传组件中回显图片）
        fileList: [{name: '', url: ''}],

        myConfig: {
          // 编辑器不自动被内容撑高
          autoHeightEnabled: false,
          // 初始容器高度
          initialFrameHeight: 500,
          // 初始容器宽度
          initialFrameWidth: '100%',
          // 上传文件接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！）
          serverUrl: '//localhost:9090/blog/server',
          // UEditor 资源文件的存放路径，如果你使用的是 vue-cli 生成的项目，通常不需要设置该选项，vue-ueditor-wrap 会自动处理常见的情况，如果需要特殊配置，参考下方的常见问题2
          UEDITOR_HOME_URL: '/static/ueditor/'
        },

        name:'img',
        id:1

      }
    },
    created() {
     
    },
    methods: {
      //保存md到后台
      save(){
        //传递name(文件名),typeId(文件所属类别),value(md文件内容）
        // var result=postMd("555","java",this.value);
        // console.log(result);
        var params = {}
        params.name = this.name
        params.typeId = this.id
        params.content = this.editForm.content
        this.postRequest("/blog/saveMd",params).then(res => {
          console.log("11111111111")
          console.log(res)
        })
        // this.dialogFormVisible = false

      },

      //保存图片到后台
      imgAdd(pos, $file){
        var _this = this;
        // 第一步.将图片上传到服务器.
        var formdata = new FormData();
        formdata.append('image', $file);
        console.log("2222222222222")
        this.postRequest('/blog/uploadFile',formdata).then(res => {
          console.log('res:'+res)
          var url = res //取出上传成功后的url
          console.log('pos:'+pos)
          _this.$refs.md.$img2Url(pos, url)
        })

        // uploadFile(formdata).then(resp=> {
        //   var url = resp.data; //取出上传成功后的url
        //   if (resp.status == 200) {
        //     //  将后端返回的url放在md中图片的指定位置
        //     console.log(url)
        //     _this.$refs.md.$img2Url(pos, url)
        //   } else {
        //     _this.$message({type: resp.status, message: resp.statusText});
        //   }
        // });
      },

      //删除标签
      handleClose(tag) {
        this.editForm.tags.splice(this.editForm.tags.indexOf(tag), 1);
      },
      //输入标签
      showInput() {
        this.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
        //回车添加标签
      handleInputConfirm() {
        let inputValue = this.inputValue;
        if (inputValue) {
          this.editForm.tags.push(inputValue);
        }
        this.inputVisible = false;
        this.inputValue = '';
      },
      //去发布文章
      toSubmit() {
        this.dialogFormVisible = true
        this.initType()
      },
      // //初始化文章专栏
      // initType() {
      //   const _this = this
      //   this.getRequest('/type/getAllType').then(resp => {
      //     console.log(resp)
      //     _this.getalltype = resp.obj
      //   })
      // },
      // 初始化文章专栏
      initType() {
        const _this = this
        this.getRequest('/type/getAll').then(resp => {
          console.log("获取到的专栏信息：")
          console.log(resp)
          _this.getalltype = resp.obj
        })
      },
      //添加新的分类专栏
      addNewType() {
        const _this = this
        this.postRequest('/type/saveType', this.type).then(resp => {
          if (resp) {
            _this.type.name = ''
            this.initType()
            _this.dialog2 = false
          }
        })
      },
      //校验添加分类专栏表单
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.addNewType()
          } else {
            return false;
          }
        });
      },
      //校验博客基本内容表单
      tosubmitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.toSubmit()
          } else {
            return false;
          }
        });
      },
      //校验发布博客表单,校验成功后发布博客
      submitBlog(formName) {
        var _this = this
        console.log(this.editForm)

        //这两个就可以分别拿去存到数据库，针对不同场景进行使用
        // console.log("判断html格式和正常模式")
        // console.log('html格式',this.$refs.md.d_render)
        // console.log('md格式',this.$refs.md.d_value)
        this.editForm.content = this.$refs.md.d_value
        this.editForm.contentHtml = this.$refs.md.d_render
        this.$refs[formName].validate((valid) => {
          if (valid) {
            //发布博客
            this.postRequest('/blog/savaBT', this.editForm).then(resp => {
              if (resp) {
                _this.dialogFormVisible = false
                this.$message({
                  type:"success",
                  message: '发布成功'
                });
                // alert("发布成功，点击确定跳转到博客列表页面!")
                _this.$router.push('/admin/allblogs')
              }
            })
          } else {
            return false;
          }
        });
      },
      //暂时保存博客
      temporarySave() {
        const _this = this
        console.log(this.editForm)
        this.postRequest('/blog/temporarySave', this.editForm).then(resp => {
          if (resp) {
            this.$message('已成功保存草稿成功');
          }
        })
      },
      //上传图片
      // 绑定@imgAdd event
      //  $imgAdd(pos, $file){
      //      console.log($file)
      //      var _this = this
      //      // 第一步.将图片上传到服务器.
      //      var formdata = new FormData();
      //      formdata.append('image', $file);
      //      this.postPicRequest('/blog/pic',formdata).then((resp) => {
      //          // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
      //          /**
      //          * $vm 指为mavonEditor实例，可以通过如下两种方式获取
      //          * 1. 通过引入对象获取: `import {mavonEditor} from ...` 等方式引入后，`$vm`为`mavonEditor`
      //          * 2. 通过$refs获取: html声明ref : `<mavon-editor ref=md ></mavon-editor>，`$vm`为 `this.$refs.md`
      //          */
      //         //  $vm.$img2Url(pos, url);
      //         console.log(resp)
      //          if(resp.status === 200){
      //             let url = resp.obj
      //             _this.$refs.md.$img2Url(pos,url) 
      //           }
      //           console.log(url) 
      //      })
      //   },


      //图片上传区

      //文件上传成功的钩子函数
      handleSuccess(res, file) {
        this.$message({
          type: 'success',
          message: '图片上传成功',
          duration: 6000
        });
        console.log("res:")
        console.log(res)
        console.log("file:")
        console.log(file)
        if (res.code == '0') {
          this.editForm.first_picture = res.data; //将返回的文件储存路径赋值picture字段
          this.hasImg = true
        }
      },
      //删除文件之前的钩子函数
      handleRemove(file, fileList) {
        this.$message({
          type: 'info',
          message: '已删除原有图片',
          duration: 6000
        });
        this.hasImg = false
      },
      //点击列表中已上传的文件事的钩子函数
      handlePreview(file) {
        console.log(file)
      },
      //上传的文件个数超出设定时触发的函数
      onExceed(files, fileList) {
        this.$message({
          type: 'info',
          message: '最多只能上传一个图片',
          duration: 6000
        });
      },
      //文件上传前的前的钩子函数
      //参数是上传的文件，若返回false，或返回Primary且被reject，则停止上传
      beforeUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isGIF = file.type === 'image/gif';
        const isPNG = file.type === 'image/png';
        const isBMP = file.type === 'image/bmp';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG && !isGIF && !isPNG && !isBMP) {
          this.$message.error('上传图片必须是JPG/GIF/PNG/BMP 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return (isJPG || isBMP || isGIF || isPNG) && isLt2M;
      },
    }
  }
</script>

<style>
  .m_container{
    margin-top: 20px;
  }
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    height: 160px;
    line-height:160px;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
</style>
